package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.ruoyi.common.utils.smsUtil.SendSmsUtil;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

public class SmsUtil {

//    public static void main(String[] args) {
//        SendSmsUtil.SendSmsRequest request = new SendSmsUtil.SendSmsRequest();
//        request.setPhone("13569234015");
//
//        request.setSmsSdkAppId("1400819568");
//
//        request.setSecretId("API的SecretId");
//        request.setSecretKey("18860663743cfcbf8ca313f517b66b93");
//
//        request.setSignName("喜悦文化");
//        request.setTemplateId("2027618");
//        // 这个值，要看你的模板中是否预留了占位符，如果没有则不需要设置
//        request.setTemplateParamSet(new String[]{});
//        SendSmsUtil.sendSms(request);
//    }

    public static Boolean sendAliYunSms(String phone, Integer code, String langId, String alisms) {
        Map<String, String> jsonMap = JSON.parseObject(alisms, new TypeReference<Map<String, String>>(){});
        DefaultProfile profile =
                DefaultProfile.getProfile("cn-hangzhou", jsonMap.get("key"),
                        jsonMap.get("secret"));
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.GET);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        request.putQueryParameter("PhoneNumbers", phone);   //手机号
        request.putQueryParameter("SignName", jsonMap.get("sign_cn"));    //签名名称
        // 如果是中文就用中文模板，不是就用英语
        JSONArray template = JSON.parseArray(jsonMap.get("template"));
        if("65".equals(langId)) {
            JSONObject jsonObject = template.getJSONObject(0);
            String value = jsonObject.getString("key");
            request.putQueryParameter("TemplateCode", value);  //模板名称
        } else {
            JSONObject jsonObject = template.getJSONObject(1);
            String value = jsonObject.getString("key");
            request.putQueryParameter("TemplateCode", value);  //模板名称
        }
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));  //验证码转换json数据

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return true;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.getMessage();
        }
        return false;
    }

//    public static void main(String[] args) throws Exception {
//
//        // HttpClient Configuration
//        /*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
//                .connectionTimeout(Duration.ofSeconds(10)) // 设置连接超时时间，默认为10秒
//                .responseTimeout(Duration.ofSeconds(10)) // 设置响应超时时间，默认为20秒
//                .maxConnections(128) // 设置连接池大小
//                .maxIdleTimeOut(Duration.ofSeconds(50)) // 设置连接池超时，默认为30秒
//                // 配置代理
//                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
//                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
//                // 如果是https连接，则需要配置证书，或者忽略证书(.ignoreSSL(true))
//                .x509TrustManagers(new X509TrustManager[]{})
//                .keyManagers(new KeyManager[]{})
//                .ignoreSSL(false)
//                .build();*/
//
//        // 配置凭据身份验证信息，包括ak、secret、token
//        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
//                // 请确保已设置环境变量ALIBAA_CLOUD_ACCESS_KEY_ID和ALIBAA_CLOUD_ACCESS_KEY_SECRET。
//                .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
//                .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
//                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
//                .build());
//
//        // Configure the Client
//        AsyncClient client = AsyncClient.builder()
//                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
//                .credentialsProvider(provider)
//                //.serviceConfiguration(Configuration.create()) // Service-level configuration
//                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
//                .overrideConfiguration(
//                        ClientOverrideConfiguration.create()
//                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
//                                .setEndpointOverride("dysmsapi.aliyuncs.com")
//                        //.setConnectTimeout(Duration.ofSeconds(30))
//                )
//                .build();
//
//        // Parameter settings for API request
//        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
//                .phoneNumbers("your_value")
//                .signName("your_value")
//                // Request-level configuration rewrite, can set Http request parameters, etc.
//                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
//                .build();
//
//        // Asynchronously get the return value of the API request
//        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
//        // Synchronously get the return value of the API request
//        SendSmsResponse resp = response.get();
//        System.out.println(new Gson().toJson(resp));
//        // Asynchronous processing of return values
//        /*response.thenAccept(resp -> {
//            System.out.println(new Gson().toJson(resp));
//        }).exceptionally(throwable -> { // Handling exceptions
//            System.out.println(throwable.getMessage());
//            return null;
//        });*/
//
//        // Finally, close the client
//        client.close();
//    }

}
